import React, { useState, useEffect, useRef } from 'react';
import { FormField } from 'types/Form.d';
import { Form, Row, Col, Button, FormInstanceFunctions, Input, Radio, Select, DateRangePicker } from 'tdesign-react';
import { SearchIcon, RefreshIcon, AddIcon } from 'tdesign-icons-react';
import { useSingleMessage } from 'composables/useMessage';
export type SearchField = {
  name: string;
  label: string;
  labelWidth?: number;
  component: React.ReactNode;
  colSpan?: number;
  onChange?: (value: any) => void;
  visible?: (formValues: any) => boolean;
  hide?: boolean;
  colWrap?: {
    colSpan?: number;
    labelWidth?: number;
  };
};
type SearchFormProps = {
  fields: SearchField[];
  onSearch?: (values: any) => void;
  onReset?: () => void;
  createField?: boolean;
  onAddClick?: () => void;
  labelWidth?: number;
  gutter?: [number, number];
  submitText?: string;
  resetText?: string;
  controls?: any;
  isRenderBtns?: string | boolean;
  hideButtons?: boolean;
  rowStyle?: React.CSSProperties;
  gutterStyle?: [number, number];
  placeholder?: string;
  onFieldClear?: (fieldName: string) => void; 
};

const { FormItem } = Form;
const SakuraSearchForm: React.FC<SearchFormProps> = ({
  fields,
  onSearch,
  onReset,
  labelWidth = 80,
  gutter = [16,16],
  submitText = '搜索',
  resetText = '重置',
  createField,
  onAddClick,
  controls,
  isRenderBtns = true,
  hideButtons = false,
  rowStyle,
  placeholder,
  gutterStyle,
  onFieldClear,
}) => {
  const createdText = '添加';
  const { showMessage } = useSingleMessage();
  const [formValues, setFormValues] = useState<any>({});
  
  const convertDateToTimestamp = (dateValue: any) => {
    if (!dateValue) return dateValue;
    
    if (Array.isArray(dateValue) && dateValue.length === 2) {
      let startTime = null;
      if (dateValue[0]) {
        const startDate = new Date(dateValue[0]);
        startDate.setHours(0, 0, 0, 0); 
        startTime = Math.floor(startDate.getTime() / 1000);
      }
      
      let endTime = null;
      if (dateValue[1]) {
        const endDate = new Date(dateValue[1]);
        endDate.setHours(23, 59, 59, 999); 
        endTime = Math.floor(endDate.getTime() / 1000);
      }
      
      return [startTime, endTime];
    }
    
    if (dateValue instanceof Date || typeof dateValue === 'string') {
      return Math.floor(new Date(dateValue).getTime() / 1000);
    }
    
    return dateValue;
  };

  const handleFieldClear = (fieldName: string) => {
    if (onFieldClear) {
      onFieldClear(fieldName);
    }
  };

  const handleFieldChange = (field: FormField, value: any) => {
    form.setFieldsValue({ [field.name as string]: value });
    
    if (field.type === 'date') {
      const timestampValue = convertDateToTimestamp(value);
      form.setFieldsValue({ [field.name as string]: value });
      setFormValues((prevValues: any) => {
        const newValues = { ...prevValues };
        
        if (value === null || value === undefined || 
            (Array.isArray(value) && value.length === 0) ||
            (Array.isArray(value) && value.every(v => v === null || v === undefined))) {
          delete newValues[field.name as string];
        } else {
          newValues[field.name as string] = timestampValue;
        }
        return newValues;
      });
      if (field.onChange) {
        field.onChange(timestampValue);
      }
    } else {
      if (field.onChange) {
        field.onChange(value);
      }
      
      form.setFieldsValue({ [field.name as string]: value });
      
      setFormValues((prevValues: any) => {
        const newValues = { ...prevValues };
        if (value === null || value === undefined || value === '') {
          delete newValues[field.name as string];
        } else {
          newValues[field.name as string] = value;
        }
        
        return newValues;
      });
      
      if (field.onChange) {
        field.onChange(value);
      }
    }
  };
  
  const renderFormItem = (field: FormField) => {
    if (field.type === 'select' && field.options) {
    }

    switch (field.type) {
      case 'select':
        return (
          <Select
            options={field.options || []}
            onChange={(value) => handleFieldChange(field, value)}
            onClear={() => {
              handleFieldChange(field, '');
              handleFieldClear(field.name as string);
            }}
            disabled={field.disabled}
            placeholder={`请选择`}
            clearable
          />
        );
      case 'input':
        return (
          <Input
            placeholder={field.placeholder || '请输入'}
            onChange={(value) => handleFieldChange(field, value)}
            onClear={() => {
              handleFieldChange(field, '');
              handleFieldClear(field.name as string);
            }}
            onBlur={() => {
              const currentValue: any = form.getFieldValue((field as any).name);
              if (typeof currentValue === 'string') {
                const trimmed = currentValue.trim();
                if (trimmed !== currentValue) {
                  form.setFieldsValue({ [(field as any).name]: trimmed });
                }
              }
            }}
            disabled={field.disabled}
            clearable
            style={{ width: field.colWrap?.width ? `${field.colWrap.width}px` : '220px' }}
          />
        );
      case 'radio':
        return (
          <Radio.Group defaultValue='gz' onChange={(value) => handleFieldChange(field, value)}>
            {(field.options || []).map((item) => (
              <Radio key={item.value} value={item.value}>
                {item.label}
              </Radio>
            ))}
          </Radio.Group>
        );
      case 'date':
        return (
          <DateRangePicker
          style={{width: '280px'}}
            onChange={(value) => {
              handleFieldChange(field, value);
              if (!value || (Array.isArray(value) && value.length === 0)) {
                handleFieldClear(field.name as string);
              }
            }}
            placeholder={['开始时间', '结束时间']}
            allowInput
            clearable
          />
        );
      default:
        return <Input />;
    }
  };

  const handleSubmit = () => {
    const formData = form.getFieldsValue(true);
    const values = { ...formData };

    fields.forEach((field: any) => {
      if (field?.type === 'date' && field?.returnType === 'timestamp') {
        const raw = values[field.name];
        if (raw !== undefined) {
          values[field.name] = convertDateToTimestamp(raw);
        }
      }
    });

    Object.keys(values).forEach((key) => {
      const v = values[key];
      if (typeof v === 'string') {
        values[key] = v.trim();
      }
      if (values[key] === null || values[key] === undefined || values[key] === '' || 
          (Array.isArray(values[key]) && values[key].length === 0)) {
        delete values[key];
      }
    });

    if (onSearch) {
      onSearch(values);
    }
  };

  const formRef = useRef<FormInstanceFunctions>();
  const [form] = Form.useForm();

  useEffect(() => {
    const initialValues: any = {};
    fields.forEach((field: any) => {
      if (field.initialValue !== undefined) {
        initialValues[field.name] = field.initialValue;
      }
    });

    if (Object.keys(initialValues).length > 0) {
      form.setFieldsValue(initialValues);
    }
  }, [fields, form]);

  const handleReset = () => {
    form.reset();
    setFormValues({});
    if (onReset) {
      onReset();
    }
    showMessage('reset');
  };

  const visibleFields = fields.filter(field => {
    if (field.visible && typeof field.visible === 'function') {
      try {
        return field.visible(formValues);
      } catch (error) {
        console.warn('Error in SakuraSearchForm field visible function:', error);
        return true;
      }
    }
    return true;
  });

  return (
    <div className='list-common-table-query'>
      {/* onSubmit={handleSubmit}  */}
      {
        <Form ref={formRef} form={form} labelWidth={labelWidth} colon onSubmit={handleSubmit}>
          <Row style={{  ...rowStyle }} gutter={ gutterStyle || gutter}>
            {visibleFields.map((field: any, index: number) => (
              <div key={index}>
                {!field.hide && (
                  <Col key={index} xl={field?.colWrap?.colSpan || 2.5}>
                    <FormItem
                      label={field.label}
                      name={field?.name}
                      labelWidth={field?.colWrap?.labelWidth || labelWidth}
                    >
                      {renderFormItem(field)}
                    </FormItem>
                  </Col>
                )}
              </div>
            ))}
            {!hideButtons && (
              <div style={{ display: 'flex', gap: '15px', marginLeft: '10px',flex:1 }}>
                {visibleFields.length >= 1 && (
                  <>
                    <Button theme='primary' type='submit' icon={<SearchIcon size='18' />}>
                      {submitText}
                    </Button>
                    <Button variant='base' theme='default' onClick={handleReset} icon={<RefreshIcon size='18' />}>
                      {resetText}
                    </Button>
                  </>
                )}
                {createField && (
                  <Button style={{marginLeft: 'auto'}} variant='base' theme='primary' onClick={onAddClick} icon={<AddIcon size='18' />}>
                    {createdText}
                  </Button>
                )}
              </div>
            )}
            <div style={{ display: 'flex', gap: '15px', margin: '0 10px' }}>
              {controls?.length >= 1 &&
                controls.map((item: any) => (
                  <Button theme={item.theme} onClick={item.onHandleClick}>
                    {item.text}
                  </Button>
                ))}
            </div>
          </Row>
        </Form>
      }
    </div>
  );
};
export default SakuraSearchForm;
